using Microsoft.AspNetCore.Mvc;
using ClassDemo.Service;
using Study1.Common;
using ClassDemo.Model.DTO;
using ClassDemo.Model.VO;
using ClassDemo.Services;
using Asp.Versioning;
using ClassDemo.DTO;
using ClassDemo.Model.Entity;

namespace ClassDemo.Controllers;

/// <summary>
/// 学生管理控制器
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/students")]
[Produces("application/json")]
public class StudentController : ControllerBase
{
    private readonly IStudentService _studentService;
    private readonly IPasswordService _passwordService;
    private readonly IJwtService _jwtService;

    public StudentController(IStudentService studentService, IPasswordService passwordService, IJwtService jwtService)
    {
        _studentService = studentService;
        _passwordService = passwordService;
        _jwtService = jwtService;
    }

    /// <summary>
    /// 获取学生列表
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="keyword">搜索关键词</param>
    /// <param name="studentNo">学号</param>
    /// <param name="className">班级</param>
    /// <param name="major">专业</param>
    /// <returns>学生列表</returns>
    [HttpGet]
    public async Task<ActionResult<ApiResult<object>>> GetStudents(
        [FromQuery] int? pageIndex = null,
        [FromQuery] int? pageSize = null,
        [FromQuery] string? keyword = null,
        [FromQuery] string? studentNo = null,
        [FromQuery] string? className = null,
        [FromQuery] string? major = null)
    {
        try
        {
            // 如果指定了学号，直接查询单个学生
            if (!string.IsNullOrEmpty(studentNo))
            {
                var student = await _studentService.GetStudentByNoAsync(studentNo);
                if (student == null)
                {
                    return NotFound(ApiResultFactory.DataNotExists("学生不存在"));
                }
                var studentVo = MapToStudentVo(student);
                return Ok(ApiResultFactory.Success(studentVo, "获取学生信息成功"));
            }

            // 如果指定了分页参数，返回分页结果
            if (pageIndex.HasValue && pageSize.HasValue)
            {
                var (data, total) = await _studentService.GetStudentsPageAsync(pageIndex.Value, pageSize.Value, keyword);
                var studentVos = data.Select(MapToStudentVo).ToList();
                var pagedResult = PagedResult<StudentVo>.Create(studentVos, total, pageIndex.Value, pageSize.Value);
                return Ok(ApiResultFactory.Success(pagedResult, "获取学生列表成功"));
            }

            // 根据条件筛选
            List<Student> students;
            if (!string.IsNullOrEmpty(className))
            {
                students = await _studentService.GetStudentsByClassAsync(className);
            }
            else if (!string.IsNullOrEmpty(major))
            {
                students = await _studentService.GetStudentsByMajorAsync(major);
            }
            else
            {
                students = await _studentService.GetAllStudentsAsync();
            }

            var studentVoList = students.Select(MapToStudentVo).ToList();
            return Ok(ApiResultFactory.Success(studentVoList, "获取学生列表成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<object>($"获取学生列表失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 根据ID获取学生
    /// </summary>
    /// <param name="id">学生ID</param>
    /// <returns>学生信息</returns>
    [HttpGet("{id:int}")]
    public async Task<ActionResult<ApiResult<StudentVo>>> GetStudent(int id)
    {
        try
        {
            var student = await _studentService.GetStudentByIdAsync(id);
            if (student == null)
            {
                return NotFound(ApiResultFactory.DataNotExists("学生不存在"));
            }
            var studentVo = MapToStudentVo(student);
            return Ok(ApiResultFactory.Success(studentVo, "获取学生信息成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<StudentVo>($"获取学生信息失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 将Student实体映射为StudentVo
    /// </summary>
    /// <param name="student">学生实体</param>
    /// <returns>学生VO</returns>
    private StudentVo MapToStudentVo(Student student)
    {
        return new StudentVo
        {
            Id = student.Id,
            No = student.No,
            Name = student.Name,
            Mobile = student.Mobile,
            Grade = student.Grade,
            Major = student.Major,
            Class = student.Class,
            Sex = student.Sex,
            CreateTime = student.CreateTime,
            UpdateTime = student.UpdateTime
        };
    }

    /// <summary>
    /// 将Student实体映射为StudentCreateResponseVo（创建时使用，不包含敏感信息）
    /// </summary>
    /// <param name="student">学生实体</param>
    /// <returns>学生创建响应VO（不包含ID、创建时间、更新时间）</returns>
    private StudentCreateResponseVo MapToStudentCreateResponseVo(Student student)
    {
        return new StudentCreateResponseVo
        {
            No = student.No,
            Name = student.Name,
            Mobile = student.Mobile,
            Grade = student.Grade,
            Major = student.Major,
            Class = student.Class,
            Sex = student.Sex
        };
    }



    /// <summary>
    /// 创建学生
    /// </summary>
    /// <param name="dto">学生信息</param>
    /// <returns>操作结果</returns>
    [HttpPost]
    public async Task<ActionResult<ApiResult<StudentCreateResponseVo>>> CreateStudent([FromBody] StudentCreateDto dto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            // 检查学号是否已存在
            var existingStudent = await _studentService.GetStudentByNoAsync(dto.No);
            if (existingStudent != null)
            {
                return Conflict(ApiResultFactory.DataExists("学号已存在"));
            }

            // 创建学生对象
            var student = new Student
            {
                No = dto.No,
                Name = dto.Name,
                Password = _passwordService.HashPassword(dto.Password),
                Mobile = dto.Mobile,
                Grade = dto.Grade,
                Major = dto.Major,
                Class = dto.Class,
                Sex = dto.Sex
            };

            var (success, message) = await _studentService.AddStudentAsync(student);
            if (success)
            {
                // 获取创建的学生信息
                var createdStudent = await _studentService.GetStudentByNoAsync(dto.No);
                var studentVo = MapToStudentCreateResponseVo(createdStudent!);
                return Ok(ApiResultFactory.Success(studentVo, "学生创建成功"));
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<StudentCreateResponseVo>($"创建学生失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 更新学生信息
    /// </summary>
    /// <param name="id">学生ID</param>
    /// <param name="dto">学生信息</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id:int}")]
    public async Task<ActionResult<ApiResult<StudentVo>>> UpdateStudent(int id, [FromBody] StudentUpdateDto dto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            // 获取现有学生信息
            var existingStudent = await _studentService.GetStudentByIdAsync(id);
            if (existingStudent == null)
            {
                return NotFound(ApiResultFactory.DataNotExists("学生不存在"));
            }

            // 检查学号是否被其他学生使用
            var studentWithSameNo = await _studentService.GetStudentByNoAsync(dto.No);
            if (studentWithSameNo != null && studentWithSameNo.Id != id)
            {
                return Conflict(ApiResultFactory.DataExists("学号已被其他学生使用"));
            }

            // 更新学生信息
            existingStudent.No = dto.No;
            existingStudent.Name = dto.Name;
            existingStudent.Mobile = dto.Mobile;
            existingStudent.Grade = dto.Grade;
            existingStudent.Major = dto.Major;
            existingStudent.Class = dto.Class;
            existingStudent.Sex = dto.Sex;
            // UpdateTime会自动填充

            // 如果提供了新密码，则更新密码
            if (!string.IsNullOrEmpty(dto.NewPassword))
            {
                existingStudent.Password = _passwordService.HashPassword(dto.NewPassword);
            }

            var (success, message) = await _studentService.UpdateStudentAsync(existingStudent);
            if (success)
            {
                var studentVo = MapToStudentVo(existingStudent);
                return Ok(ApiResultFactory.Success(studentVo, "学生信息更新成功"));
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<StudentVo>($"更新学生信息失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 删除学生
    /// </summary>
    /// <param name="id">学生ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id:int}")]
    public async Task<ActionResult<ApiResult>> DeleteStudent(int id)
    {
        try
        {
            // 先检查学生是否存在
            var existingStudent = await _studentService.GetStudentByIdAsync(id);
            if (existingStudent == null)
            {
                return NotFound(ApiResultFactory.DataNotExists("学生不存在"));
            }

            var (success, message) = await _studentService.DeleteStudentAsync(id);
            if (success)
            {
                return NoContent(); // 204 No Content - 删除成功
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail($"删除学生失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 批量删除学生
    /// </summary>
    /// <param name="request">批量删除请求</param>
    /// <returns>操作结果</returns>
    [HttpDelete]
    public async Task<ActionResult<ApiResult>> DeleteStudents([FromBody] BatchDeleteRequest request)
    {
        try
        {
            if (request?.Ids == null || !request.Ids.Any())
            {
                return BadRequest(ApiResultFactory.BadRequest("请提供要删除的学生ID列表"));
            }

            var (success, message) = await _studentService.DeleteStudentsAsync(request.Ids);
            if (success)
            {
                return Ok(ApiResultFactory.Success(message));
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail($"批量删除学生失败：{ex.Message}"));
        }
    }


}